<template>
  <div class="museum-creative">
    <!-- 导航栏 -->
    <div class="nav-container">
      <div class="logo">
        <span class="logo-text">文创</span>
      </div>
      <ul class="nav-menu">
        <li class="nav-item">
          <!-- <a href="#" class="nav-link active">首页</a> -->
          <router-link to="/museum" class="nav-link" @click.prevent="home">首页</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/allproducts" class="nav-link">查看全部</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/consultation" class="nav-link" >文化资讯</router-link>
        </li>
        <li class="nav-item">
          <router-link v-if="!isLoggedIn()" to="/login" class="nav-link">登录</router-link>
          <router-link v-if="isLoggedIn()" to="/museum" class="nav-link" @click.prevent="logout">退出</router-link>
        </li>
        <li class="nav-item">
          <a class="nav-link cart-icon" @click.prevent="openShoppingCart">
            <img src="@/assets/img/btn_waiter_sel.png" alt="购物车" class="cart-img">
            <span v-if="cartItemCount > 0" class="cart-badge">{{ cartItemCount }}</span>
          </a>
        </li>
      </ul>
    </div>

    <!-- 轮播图 -->
    <div class="carousel fade-in">
      <img :src="carouselImages[currentSlide]" alt="博物馆文创" class="carousel-image">
    </div>

    <!-- 推荐商品 -->
    <div class="products-section fade-in">
      <h2 class="section-title">
        精选推荐
        <router-link to="/allproducts" class="view-all">查看全部</router-link>
      </h2>
      <div class="products-grid">
        <div v-for="(product, index) in featuredProducts" :key="index" class="product-card"
          @click="viewProductDetail(product)">
          <div class="product-image-container">
            <img :src="getImageUrl(product.image)" :alt="product.name" class="product-image">
          </div>
          <div class="product-details">
            <h3 class="product-name">{{ product.name }}</h3>
            <div class="product-price">¥ {{ product.price.toFixed(2) }}</div>
            <button class="add-to-cart" @click.stop="addToCart(product)">
              <span class="icon">+</span>
              加入购物车
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 新品上市 -->
    <div class="products-section fade-in">
      <h2 class="section-title">
        新品上市
        <router-link to="/allproducts" class="view-all">查看全部</router-link>
      </h2>
      <div class="products-grid">
        <div v-for="(product, index) in newProducts" :key="index" class="product-card"
          @click="viewProductDetail(product)">
          <div class="product-image-container">
            <img :src="getImageUrl(product.image)" :alt="product.name" class="product-image">
          </div>
          <div class="product-details">
            <h3 class="product-name">{{ product.name }}</h3>
            <div class="product-price">¥ {{ product.price.toFixed(2) }}</div>
            <button class="add-to-cart" @click.stop="addToCart(product)">
              <span class="icon">+</span>
              加入购物车
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品详情(默认隐藏) -->
    <div v-if="showProductDetail" class="product-detail fade-in">
      <div class="product-gallery">
        <img :src="getImageUrl(selectedProduct.image)" :alt="selectedProduct.name" class="main-image">
        <div class="thumbnail-container">
          <img v-for="(img, index) in selectedProduct.images" :key="index" :src="img"
            :alt="selectedProduct.name + ' 图片 ' + (index + 1)" class="thumbnail"
            :class="{ active: index === selectedImageIndex }" @click="selectedImageIndex = index">
        </div>
      </div>
      <div class="product-info">
        <h1 class="product-title">{{ selectedProduct.name }}</h1>
        <div class="price-container">
          <span class="current-price">¥ {{ selectedProduct.price.toFixed(2) }}</span>
          <span v-if="selectedProduct.originalPrice" class="original-price">
            ¥ {{ selectedProduct.originalPrice.toFixed(2) }}
          </span>
          <span v-if="selectedProduct.discount" class="discount-tag">
            {{ selectedProduct.discount }}折
          </span>
        </div>
        <p class="product-description">{{ selectedProduct.description }}</p>

        <div class="quantity-selector">
          <span class="quantity-label">数量</span>
          <div class="quantity-controls">
            <button class="quantity-btn" @click="decreaseQuantity">-</button>
            <input type="number" v-model="quantity" min="1" class="quantity-input">
            <button class="quantity-btn" @click="increaseQuantity">+</button>
          </div>
        </div>

        <div class="action-buttons">
          <!-- 立即购买按钮，flex布局，宽度自适应 -->
          <button class="buy-now" @click="buyNow(selectedProduct)">立即购买</button>
          <!-- 加入购物车按钮，flex布局，宽度自适应 -->
          <button class="add-to-cart-detail" @click="addToCart(selectedProduct)">加入购物车</button>
        </div>
        <!-- 评价商品按钮，宽度与action-buttons一致，整体下移 -->
        <div class="appraise-wrapper">
          <button class="appraise" @click="appraise(selectedProduct)">评价商品</button>
        </div>

      </div>
    </div>

    <!-- 用户评价部分 -->
    <div v-if="showProductDetail" class="reviews-section fade-in" @click="appraiselist(selectedProduct)">
      <h2 class="section-title">用户评价</h2>
      <div class="review-card" v-for="(review, index) in reviews" :key="index">
        <div class="reviewer-info">
          <span class="reviewer-name">{{ review.username }}</span>
          <span class="review-date">{{ review.date }}</span>
        </div>
        <div class="rating">
          <span v-for="i in review.rating" :key="i">★</span>
          <span v-for="i in 5 - review.rating" :key="'empty-' + i" class="empty-star">☆</span>
        </div>
        <p class="review-text">{{ review.content }}</p>
      </div>
    </div>
  </div>


  <div v-if="showReviewForm">
    <form @submit.prevent="submitForm" class="review-form">
      <h3>商品评价</h3>
      <button type="button" class="close-btn" @click="closeReviewForm">&times;</button>
      <div>
        <label for="rating" class="rating-label">评分:</label>
        <select v-model="rating" id="rating">
          <option value="1">1星</option>
          <option value="2">2星</option>
          <option value="3">3星</option>
          <option value="4">4星</option>
          <option value="5">5星</option>
        </select>
      </div>
      <div>
        <label for="content">评价内容:</label>
        <textarea v-model="content" id="content" rows="4" placeholder="请分享您对商品的使用体验..." required></textarea>
      </div>
      <div>
        <button type="submit">提交评价</button>
      </div>
    </form>
  </div>
  <router-view />
</template>

<script setup>
// 导入所需的组件和库
import api from '@/assets/js/api.js'; // 导入API接口
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, computed } from 'vue'; // 导入Vue组合式API
import { useRouter } from 'vue-router'; // 导入路由
import { ElMessage } from 'element-plus'; // 导入Element Plus的消息提示

// 获取路由实例
const router = useRouter();

// 轮播图数据
const carouselImages = [
  new URL('@/assets/img/1.png', import.meta.url).href,
  new URL('@/assets/img/2.png', import.meta.url).href,
];
const currentSlide = ref(0);
let carouselInterval = null;

// 商品数据
const allProducts = ref([]); // 存储所有从API获取的商品
const featuredProducts = ref([]); // 精选推荐商品
const newProducts = ref([]); // 新品上市商品

// 产品详情相关数据
const showProductDetail = ref(false);
const selectedProduct = ref({});
const selectedImageIndex = ref(0);
const quantity = ref(1);

// 用户评价
const reviews = ref([]);

// 评价表单数据
const rating = ref("5");
const content = ref("");
const showReviewForm = ref(false);

// 购物车数量
const cartItemCount = ref(0);

// 页面加载时获取商品数据
fetchProducts();

// 组件挂载后启动轮播图
onMounted(() => {
  startCarousel();

});

// 组件卸载前清除定时器
onBeforeUnmount(() => {
  stopCarousel();
});

// 首页刷新
function home() {
  window.location.reload();
}

// 检查用户是否已登录
function isLoggedIn() {
  // 检查localStorage中是否存在userId
  return localStorage.getItem('userId');
  
}

// 退出登录
async function logout() {
  const result = await api.out();
  if (result.data == "退出成功") {
    localStorage.clear();
    location.reload();
  }
}

// 提交评价表单
async function submitForm() {
  const reviewData = {
    rating: Number(rating.value),
    content: content.value,
    productId: selectedProduct.value.id, // 关联的商品ID
    userId: Number(localStorage.getItem('userId')), // 用户ID从localStorage获取
  };
  await api.addReview(reviewData);
  showReviewForm.value = false;
  window.location.reload();
}

// 获取商品评论
async function appraiselist(product) {
  const result = await api.getProductReviews(product.id);
  if (result.code === 200 && result.data) {
    reviews.value = result.data.map(item => ({
      username: item.username,
      content: item.content,
      rating: item.rating,
      date: item.date || '刚刚'
    }));
  }
}

// 获取商品数据
async function fetchProducts() {
  try {
    const result = await api.product();
    if (result.code === 200 && result.data) {
      allProducts.value = result.data;
      // 分配前4个商品为精选推荐
      featuredProducts.value = allProducts.value.filter(product => product.id <= 4);
      // 分配后4个商品为新品上市
      newProducts.value = allProducts.value.filter(product => product.id > 4);
    }
  } catch (error) {
    console.error('获取商品数据失败:', error);
  }
}

// 补全图片地址
function getImageUrl(imagePath) {
  return `http://localhost:8080${imagePath}`;
}

// 轮播图方法
function startCarousel() {
  carouselInterval = setInterval(() => {
    currentSlide.value = (currentSlide.value + 1) % carouselImages.length;
  }, 5000); // 每5秒切换一次
}

function stopCarousel() {
  clearInterval(carouselInterval);
}

// 查看商品详情
function viewProductDetail(product) {
  selectedProduct.value = product;
  selectedImageIndex.value = 0;
  quantity.value = 1;
  showProductDetail.value = true;
  // 滚动到详情部分
  nextTick(() => {
    const detailElement = document.querySelector('.product-detail');
    if (detailElement) {
      detailElement.scrollIntoView({ behavior: 'smooth' });
    }
  });
  appraiselist(selectedProduct.value);
}

// 数量控制
function increaseQuantity() {
  quantity.value++;
}

function decreaseQuantity() {
  if (quantity.value > 1) {
    quantity.value--;
  }
}


// 添加到购物车
async function addToCart(product) {
  if (!isLoggedIn()) {
    // 用户未登录，提示登录
    ElMessage.warning('请先登录后再添加商品到购物车');
    router.push('/login');
    return;
  }
  
  try {
    const cartItem = {
      userId: Number(localStorage.getItem('userId')),
      productId: product.id,
      productName: product.name,
      productImage: product.image,
      price: product.price,
      quantity: quantity.value,
    }
    // TODO: 如果需要，可以在这里添加与后端的交互
    await api.addToCart(cartItem);
    
    // 提示添加成功
    ElMessage.success(`${product.name} 已添加到购物车`);
  } catch (error) {
    console.error('添加到购物车失败:', error);
    ElMessage.error('添加到购物车失败');
  }
}

// 立即购买
function buyNow(product) {
  // 添加到购物车
  addToCart(product);
  // 跳转到购物车页面
  router.push('/shoppingcart');
}

// 打开购物车页面
function openShoppingCart() {
  router.push('/shoppingcart');
}

// 评价商品
function appraise(product) {
  selectedProduct.value = product;
  showReviewForm.value = true;
}

// 关闭评价表单
function closeReviewForm() {
  showReviewForm.value = false;
}
</script>

<style scoped>
/* 引入CSS文件 */
@import '../../assets/css/museum-product.css';
</style>